// src/store/darkTheme.ts
import { defineStore } from 'pinia'
const _darkTheme = 'theme'
export const useThemeStore = defineStore(_darkTheme, {
  state: () => ({
    // 初始状态：优先读取本地存储，无则匹配系统主题
    isDark: localStorage.getItem(_darkTheme)
      ? localStorage.getItem(_darkTheme) === 'dark'
      : window.matchMedia('(prefers-color-scheme: dark)').matches,
  }),
  actions: {
    initTheme() {
      const savedTheme = localStorage.getItem(_darkTheme)
      if (savedTheme) {
        this.isDark = savedTheme === 'dark'
      } else {
        this.isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      }
      localStorage.setItem(_darkTheme, this.isDark ? 'dark' : 'light')
      this.updateHtmlClass()
    },
    destroyTheme() {},
    // 切换暗黑模式
    toggleDarkMode() {
      this.isDark = !this.isDark
      // 更新本地存储
      localStorage.setItem(_darkTheme, this.isDark ? 'dark' : 'light')
      // 更新 HTML 根元素的 class（控制 Tailwind 暗黑模式）
      this.updateHtmlClass()
    },
    // 初始化 HTML 根元素 class
    updateHtmlClass() {
      const html = document.documentElement
      if (this.isDark) {
        html.classList.add('tw-dark')
        html.classList.remove('tw-light')
        html.setAttribute('data-theme', 'dark')
      } else {
        html.classList.remove('tw-dark')
        html.classList.add('tw-light')
        html.setAttribute('data-theme', 'light')
      }
    },
  },
  getters: {
    // 获取当前主题模式文本（可选）
    themeText: (state) => (state.isDark ? '暗黑模式' : '亮色模式'),
  },
})
